package cn.doitedu.dw.hive.udf;

import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.io.Text;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2021/9/28.
 */
public class EventStringSort extends GenericUDF {

    @Override
    public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {

        if(objectInspectors.length!=1){
            throw new UDFArgumentException("参数个数必须是1");
        }

        if(!StringUtils.equalsAnyIgnoreCase(objectInspectors[0].getTypeName(),"string")){
            throw new UDFArgumentException("第一个参数类型必须为string");
        }

        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;
    }

    /**
     *
     * @param deferredObjects
     * @return
     * @throws HiveException
     */
    @Override
    public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {


        DeferredObject deferredObject = deferredObjects[0];

        Text fieldValue = (Text)deferredObject.get();


        String[] split = fieldValue.toString().split(",");

        List<String> lst = Arrays.asList(split);

        Collections.sort(lst, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.compare(Integer.valueOf(o1),Integer.valueOf(o2));
            }
        });

        //排序后，重新组合成String返回
        StringBuilder builder=new StringBuilder();

        lst.stream().forEach(x->{
            builder.append(x).append(",");
        });
        return StringUtils.removeEnd(builder.toString(),",");
    }

    @Override
    public String getDisplayString(String[] strings) {
        return "对字符串进行排序";
    }
}
